$package("common.tools.scheduledTask");
$import("common.tools.scheduledTask.scheduledTask")
$import('itsm.itsop.selectCompany');
if(isCIHave){
	$import("itsm.cim.configureItemUtil");
}
$import("common.config.dictionary.dataDictionaryUtil");
$import("common.config.category.eventCategoryTree");
$import("common.security.userUtil");
$import("common.eav.attributes");
$import("common.tools.schedule.setMonthly");
$import("common.knowledge.knowledgeTree");
$import('common.config.category.serviceCatalog');
$import('common.security.xssUtil');
/**
 * @author QXY
 * @constructor users
 * @description 定期任务编辑
 * @date 2011-10-11
 * @since version 1.0
 */
common.tools.scheduledTask.editScheduledTask=function(){
	this.rowHTML='<tr id="ref_ci_CIID">'+
	'<td align="center">CINO</td>'+
	'<td align="center"><input type="hidden" name="cinos" value="CIID" />'+
	'<a href=javascript:common.tools.scheduledTask.editScheduledTask.lookConfigureItemInfo(CIID)>CINAME</a>'+
	'</td>'+
	'<td align="center">CATEGORYNAME</td>'+
	'<td align="center">CISTATUS</td>'+
	'<td align="center"><a onclick=itsm.cim.configureItemUtil.removeRow("#ref_ci_CIID")>DELETE</a></td>'+
	'</tr>';
	return {
		/**
		 * @description 格式化值
		 */
		inputSetValue:function(value){
			if(value==null || value=='null')
				return '';
			else
				return value;
		},
		/**
		 * @description 选择请求分类
		 * @param showAttrId 显示div的id
		 * @param dtoName 
		 */
		selectEditRequestCategory:function(showAttrId,dtoName){
			common.config.category.eventCategoryTree.showSelectTree('#request_category_select_window'
					,'#request_category_select_tree'
					,'Request'
					,'#edit_scheduledTask_categoryName'
					,'#edit_scheduledTask_categoryNo'
					,''
					,'',showAttrId,dtoName);
			
		},
		/**
		 * 根据ID查询定期任务
		 * @param 定期任务id
		 */
		findScheduledTaskById:function(id){
			var _url = 'scheduledTask!findScheduledTaskById.action';
			$.post(_url,'queryDTO.scheduledTaskId='+id,function(data){
				if(data!=null){
					// 所属客户
					$('#edit_scheduledTask_companyNo').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.requestDTO.companyNo));
					$('#edit_scheduledTask_companyName').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.requestDTO.companyName));
					// 标题
					$('#edit_scheduledTask_etitle').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.requestDTO.etitle));
					// 内容
					initCkeditor('edit_scheduledTask_edesc','Simple',function(){
						var oEditor = CKEDITOR.instances.edit_scheduledTask_edesc;
						oEditor.setData(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.requestDTO.edesc));
					});
						
					$('#edit_scheduledTask_edesc').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.requestDTO.edesc));
					// 分类
					$('#edit_scheduledTask_categoryNo').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.requestDTO.ecategoryNo));
					$('#edit_scheduledTask_categoryName').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.requestDTO.ecategoryName));
					
					// 请求人
					$('#edit_scheduledTask_createdNo').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.requestDTO.createdByNo));
					$('#edit_scheduledTask_createdName').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.requestDTO.createdByName));
					$.post("event!findByIdCategorys.action",{"categoryId":data.requestDTO.ecategoryNo},function(res){
						itsm.cim.ciCategoryTree.showAttributet(res.eavId,"scheduledTask_edit_eavAttributet","requestDTO");
						setTimeout(function(){
							if(data.requestDTO.attrVals!=null){
								for(var key in data.requestDTO.attrVals){
									$("#"+key+"scheduledTask_edit_eavAttributet").val(data.requestDTO.attrVals[key]);
								}
							}else{
								$('#scheduledTask_edit_eavAttributet').html("");
							}
						},500);
					});
					
					setTimeout(function(){
						
						// 来源
						if(data.requestDTO.imodeNo!=null)
							$('#edit_scheduledTask_imode').val(data.requestDTO.imodeNo);
						// 优先级
						if(data.requestDTO.priorityNo!=null)
							$('#edit_scheduledTask_priority').val(data.requestDTO.priorityNo);
						// 复杂程度
						if(data.requestDTO.levelNo!=null)
							$('#edit_scheduledTask_level').val(data.requestDTO.levelNo);
						// 影响
						if(data.requestDTO.effectRangeNo!=null)
							$('#edit_scheduledTask_effectRange').val(data.requestDTO.effectRangeNo);
						// 紧急度
						if(data.requestDTO.seriousnessNo!=null)
							$('#edit_scheduledTask_seriousness').val(data.requestDTO.seriousnessNo);
					},500);
					// 配置项
					if(data.requestDTO.relatedConfigureItemNos!=null){
						var ids =data.requestDTO.relatedConfigureItemNos;
						var param = $.param({"ids":ids},true);
						$.post("ci!findByIds.action",param,function(ci){
							if(ci!=null){
								var cigDTO=ci;
								for(var i=0;i<cigDTO.length;i++){
									var status='';
									if(cigDTO[i].status!=null)
										status=cigDTO[i].status;
									var newRowHTML=rowHTML.replace(/CIID/g,cigDTO[i].ciId)
									.replace(/CINO/g,cigDTO[i].cino)
									.replace(/CIDETAIL_TITLE/g,i18n['ci_configureItemInfo'])
									.replace(/CINAME/g,cigDTO[i].ciname)
									.replace(/CATEGORYNAME/g,cigDTO[i].categoryName)
									.replace(/CISTATUS/g,status)
									.replace(/DELETE/g,i18n['deletes']); 
									$(newRowHTML).appendTo('#scheduledTask_edit_relatedCIShow tbody');
								}
							}
						});
					}
					// 所属服务
					if(data.requestDTO.requestServiceDirNo!=null){
						var ids =data.requestDTO.requestServiceDirNoStrs;
						var param="";
						if(ids == null || ids == ''){
							var idsNo=data.requestDTO.requestServiceDirNo;
							if(idsNo != null && idsNo != 0){
								param = $.param({"categoryNos":data.requestDTO.requestServiceDirNo},true);
							}
						}else{
							var ids1 = ids.split(",");
							param = $.param({"categoryNos":ids1},true);
						}
						if(param!=""){
							$.post("event!findScheduledCategoryArray.action",param,function(res){
								if(res != null){
									for ( var i = 0; i < res.length; i++) {
										$("<tr id=edit_scheduledTask_"+res[i].eventId+"><td>"+res[i].eventName+"</td><td>"+res[i].scores+"</td><td><a onclick=common.knowledge.knowledgeTree.serviceRm("+res[i].eventId+")>"+i18n['deletes']+"</a><input type=hidden name=serviceDirNos value="+res[i].eventId+"></td></tr>").appendTo('#edit_scheduledTask_serviceDirectory_tbody');
									}
								}
							});
						}
					}
					/*
					 * $('#edit_scheduledTask_ref_requestServiceDirNo').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.requestDTO.requestServiceDirNo));
					 * $('#edit_scheduledTask_ref_requestServiceDirName').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.requestDTO.requestServiceDirName));
					 */
					// 时间表
					$('#edit_scheduledTask_startDate_input').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(timeFormatterOnlyData(data.taskDate)));
					$('#edit_scheduledTask_endDate_input').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(timeFormatterOnlyData(data.taskEndDate)));
					if(data.timeType=='day'){// 日计划
						$('#timeType_day').attr('checked',true);
						common.tools.scheduledTask.scheduledTask.everyWhatChange('day','edit_')
						$('#edit_scheduledTask_hours').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.taskHour));
						$('#edit_scheduledTask_minute').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.taskMinute));
					}
					if(data.timeType=='weekly'){// 周计划
						common.tools.scheduledTask.scheduledTask.everyWhatChange('weekly','edit_')
						$('#timeType_weekly').attr('checked',true);
						$('#edit_scheduledTask_hours').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.taskHour));
						$('#edit_scheduledTask_minute').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.taskMinute));
						var weekWeeks=data.weekWeeks;
						
						if(weekWeeks!=null && weekWeeks!=''){
							var weekWeekArray=weekWeeks.split(',');
							for(var i=0;i<weekWeekArray.length;i++){
								$('#request_checkbox_'+trim(weekWeekArray[i])).attr('checked',true);
							}
						}
						
					}
					
					if(data.timeType=='month'){// 月计划
						
						$('#timeType_month').attr('checked',true);
						common.tools.scheduledTask.scheduledTask.everyWhatChange('month','edit_')
						$('#edit_scheduledTask_monthDay').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.monthDay));
						$('#edit_scheduledTask_hours').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.taskHour));
						$('#edit_scheduledTask_minute').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.taskMinute));
						
						var monthMonths=data.monthMonths;
						common.tools.schedule.setMonthly.setmonthDayForEdit('edit_scheduledTask_monthDay',monthMonths);
						$('#edit_scheduledTask_monthDay').val(data.monthDay);
						if(monthMonths!=null && monthMonths!=''){
							var monthMonths=monthMonths.split(',');
							for(var i=0;i<monthMonths.length;i++){
								$('#request_checkbox_'+trim(monthMonths[i])).attr('checked',true);
							}
						}
					}
					if(data.timeType=='cycle'){// 周期性计划
						$('#timeType_cycle').attr('checked',true);
						common.tools.scheduledTask.scheduledTask.everyWhatChange('cycle','edit_')
						$('#edit_scheduledTask_cyclicalDay').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.cyclicalDay));
						$('#edit_scheduledTask_hours').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.taskHour));
						$('#edit_scheduledTask_minute').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.taskMinute));
					}
					if(data.timeType=='cycleMinute'){// 周期性计划(分钟)
						$('#timeType_cycleMinute').attr('checked',true);
						common.tools.scheduledTask.scheduledTask.everyWhatChange('cycleMinute','edit_')
						$('#edit_scheduledTask_cyclicalMinute').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.cyclicalMinute));
						$('#edit_scheduledTask_cyclicalDay').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.cyclicalDay));
						$('#edit_scheduledTask_hours').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.taskHour));
						$('#edit_scheduledTask_minute').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.taskMinute));
					}
					if(data.timeType=='on_off'){// 一次性计划
						$('#timeType_on_off').attr('checked',true);
						common.tools.scheduledTask.scheduledTask.everyWhatChange('on_off','edit_')
						$('#edit_scheduledTask_hours').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.taskHour));
						$('#edit_scheduledTask_minute').val(common.tools.scheduledTask.editScheduledTask.inputSetValue(data.taskMinute));
					}
					
					// 附件
					if(data.requestDTO.attachmentStr!=null){
						$('#edit_scheduledTask_attachmentStr').val(data.requestDTO.attachmentStr);
						var str="<div id='{id}'><a>{attachmentName}</a><a href=javascript:deleteFile('{attachmentStr}','#edit_scheduledTask_success_attachment','#edit_scheduledTask_attachmentStr')>&nbsp;&nbsp;"+i18n['deletes']+"</a></div>";
						var attachmentStr=data.requestDTO.attachmentStr;
						if(attachmentStr.indexOf('-s-')!=-1){
							var attrArr=attachmentStr.split('-s-');
							for(var i=0;i<attrArr.length;i++){
								var url=attrArr[i].replace("\\","/");
			        			if(url!=null && url!=''){
			            			var attrArrs=url.split("==");
			            			var strid=attrArrs[1].substring(attrArrs[1].indexOf("/")+1,attrArrs[1].indexOf("."))
			            			$('#edit_scheduledTask_success_attachment').append(str.replace('{id}',strid).replace('{attachmentName}',attrArrs[0]).replace('{attachmentStr}',attrArrs[1]));
			            			// deleteFile('20111018/1318927080403.txt','#edit_scheduledTask_success_attachment','#edit_scheduledTask_attachmentStr')
			        			}
							}
						}
					}

				}
			})
		},
		/**
		 * 打开配置项详情
		 * @param 配置项id
		 */
		lookConfigureItemInfo:function(ciId){
			basics.tab.tabUtils.reOpenTab("ci!findByciId.action?ciEditId="+ciId,i18n['ci_configureItemInfo'])
		},
		
		/**
		 * 保存定期任务
		 */
		editScheduledTask:function(){
			if($('#edit_scheduledTask_eavAttributet_form').form('validate')){
				if($('#editScheduledTimeSettings form').form('validate')){
					if($('#editScheduledTaskForm').form('validate')){
						if($("#editScheduledTimeSettings input[name='scheduledTaskDTO.timeType']:checked").val() == "month" && $("#edit_scheduledTask_monthDay").val()==null){
							msgAlert(i18n.scheduledTask_monthPlan_monthDayIsNotNull,'info');
						}else{
							var myDate=new Date() 
				    		var month=myDate.getMonth()+1;
							if(!DateComparison($('#edit_scheduledTask_endDate_input').val(),myDate.getFullYear()+'-'+month+'-'+(myDate.getDate()-1))){
								var _edesc="";
								if(CKEDITOR.instances['edit_scheduledTask_edesc']){
									var oEditor = CKEDITOR.instances.edit_scheduledTask_edesc;
									_edesc = oEditor.getData();
								}
								var bool=trim(_edesc)==''?false:true;
								if(!bool){
									msgAlert(i18n['titleAndContentCannotBeNull'],'info');
								}else{
									$('#edit_scheduledTask_edesc').val(_edesc);
									var frm = $('#editScheuledTaskDiv form').serialize();
									var _url = 'scheduledTask!editScheduledTask.action';
									// 调用
									startProcess();
									$.post(_url,frm,function(res){
											endProcess();
											basics.tab.tabUtils.closeTab(i18n['title_edit_scheuledTask']);
											
											basics.tab.tabUtils.addTab(i18n['title_scheduled_task_manage'],'../pages/common/tools/scheduledTask/scheduledTasksManage.jsp');
											$('#scheduledTasksGrid').trigger('reloadGrid');
											msgShow(i18n['msg_edit_successful'],'show');
										
									});
								}
							}else{
								msgAlert(i18n['tip_endTime_cannot_be_before_startTime'],'info');
								$('#editScheduledTask_tab').tabs('select', '*'+i18n.scheduledTask_time_setting);
							}
						}
					}
				}else{
					$('#editScheduledTask_tab').tabs('select', '*'+i18n.scheduledTask_time_setting);
				}
			}else{
				msgAlert(i18n.eavAttributet_notNull,'info');
				$('#editScheduledTask_tab').tabs('select', i18n.config_extendedInfo);
			}
		},
		
		/**
		 * @description 选择请求分类.
		 */
		selectRequestCategory:function(){

			common.config.category.eventCategoryTree.showSelectTree('#request_category_select_window'
					,'#request_category_select_tree'
					,'Request'
					,'#edit_scheduledTask_categoryName'
					,'#edit_scheduledTask_categoryNo');
			
		},
		/**
		 * @description 点击tab后，根据tab标题加载不同的数据
		 * @param title 标题
		 */
		tabClickEvents:function(title){
			if(title==i18n["config_extendedInfo"]){// 扩展属性
				(eno,'itsm.request',res.categoryEavId,'scheduledTask_edit_eavAttributet','request')
				common.eav.attributes.findAttributeByEno(scheduledTaskId,'request','scheduledTask_edit_eavAttributet');// 加载
			}
		},
		/**
		 * @description 初始化
		 */
		init:function(){
			// 绑定日期控件
			DatePicker97(['#edit_scheduledTask_startDate_input','#edit_scheduledTask_endDate_input']);
			$("#editScheduledTask_loading").hide();
			$("#editScheduledTask_panel").show();
			// 设定月份总天数
			//common.tools.schedule.setMonthly.setmonthDay('edit_everyWhat_monthly','edit_scheduledTask_monthDay');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('effectRange','#edit_scheduledTask_effectRange');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('seriousness','#edit_scheduledTask_seriousness');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('imode','#edit_scheduledTask_imode');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('level','#edit_scheduledTask_level');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('priority','#edit_scheduledTask_priority');
			
			setTimeout(function(){
				getUploader('#edit_scheduledTask_file','#edit_scheduledTask_attachmentStr','#edit_scheduledTask_success_attachment','');
			},0)
		
			$('#edit_scheduledTask_companyName').click(function(){// 选择公司
				itsm.itsop.selectCompany.openSelectCompanyWin('#edit_scheduledTask_companyNo','#edit_scheduledTask_companyName','#edit_scheduledTask_createdName,#edit_scheduledTask_createdNo');
			});
			// $('#edit_scheduledTask_categoryName').click(common.tools.scheduledTask.editScheduledTask.selectRequestCategory);
			
			$('#edit_scheduledTask_createdName').click(function(){
				common.security.userUtil.selectUser('#edit_scheduledTask_createdName','#edit_scheduledTask_createdNo','','loginName',$('#edit_scheduledTask_companyNo').val());
			})
			
			// 绑定选择配置项
			$('#edit_scheduledTask__ref_ci_btn').click(function(){
				itsm.cim.configureItemUtil.requestSelectCI('#scheduledTask_edit_relatedCIShow',$('#edit_scheduledTask_companyNo').val(),'');
			});
			
			$('#editScheduledTaskBtn').click(common.tools.scheduledTask.editScheduledTask.editScheduledTask);// 保存定期任务
			
			$('#edit_scheduledTask_backList').click(function(){
				basics.tab.tabUtils.addTab(i18n['title_scheduled_task_manage'],'../pages/common/tools/scheduledTask/scheduledTasksManage.jsp');
			});// 返回列表
			
			
			$('#edit_scheduledTask_service_add').click(function(){
				common.config.category.serviceCatalog.selectServiceDir('#edit_scheduledTask_serviceDirectory_tbody');
			});
			
		}
	}
}();
$(document).ready(common.tools.scheduledTask.editScheduledTask.init);
